package com.atguiguNIO.channel;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;

public class DatagramChannel02 {



    public static void main(String[] args) {
        try {
            DatagramChannel channel = DatagramChannel.open();
            channel.configureBlocking(false);

            Selector selector = Selector.open();
            channel.register(selector, SelectionKey.OP_WRITE);
            int keyCount = selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectionKeys.iterator();
            while (it.hasNext()) {
                SelectionKey key = it.next();
                if (key.isWritable()) {

                    //如果在两台物理计算机中进行实验，则要把localhost改成客户端的IP地址
                    for (int i = 0; i < 10; i++) {
                        ByteBuffer byteBuffer = ByteBuffer.wrap("你大爷的！".getBytes());
                        channel.send(byteBuffer, new InetSocketAddress("localhost", 8080));
                        Thread.sleep(2000);
                    }
                    channel.close();
                }
            }
            System.out.println("client 发送完毕!");
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }


}
